<template>
  <div class="layout-parent w100 p10">
    <el-tabs type="border-card">
      <el-tab-pane>
        <template #label><vp-label zh="基本信息" en="Basic Info"/></template>
        <VoluntaryDept :id="businessId" :type="'audit'" ref="taskRef" @dataEmits="getData"></VoluntaryDept>
        <vp-card>
          <template #header><vp-label zh="处理结果" en="Handling Result"/></template>
          <el-form ref="processExtFormRef" label-suffix=":" :model="processExtFormData"  label-width="120px" class="w100">
              <el-row>
                <vp-col :span="1" v-if="isValid ">
                  <el-form-item  prop="cnbs" :rules="[validateUtils.notNull]">
                    <template #label><vp-label zh="是否采纳" en="Whether Adopt"/></template>
                        <el-radio-group v-model="processExtFormData.cnbs" >
                          <el-radio :label="0"><vp-label zh="确认无效/不采纳，关闭本报告" en="Confirmed invalid/not adopted, close this report"/></el-radio>
                          <el-radio :label="1"><vp-label zh="确认有效，采纳" en="Confirmed effective, adopted"/></el-radio>
                        </el-radio-group>
                  </el-form-item>
              </vp-col>
              </el-row>
              <el-row>
                <vp-col :span="1" v-if="isValid  && processExtFormData.cnbs == 0">
                  <el-form-item prop="cnsm">
                    <template #label><vp-label zh="不采纳原因" en="Reason"/></template>
                    <el-input
                          v-model="processExtFormData.cnsm"
                          maxlength="1300"
                          :autosize="{ minRows: 3}"
                          type="textarea"
                      />
                  </el-form-item>
                </vp-col>
              </el-row>
              <el-row v-if="isValid && formData.jb == 10 && formData.lx == 10 && processExtFormData.cnbs == 1">
                  <vp-col :span="4">
                    <el-form-item prop="zrbm" :rules="[validateUtils.notNull]">
                      <template #label><vp-label zh="责任部门" en="Responsible Dept."/></template>
                          <el-input
                            v-model="processExtFormData.zrbm"
                            @blur="processExtFormData.zrbm = $event.target.value.trim()"
                            readonly
                          >
                          <template #append>
                            <el-button @click="handleSearchDprt(processExtFormData)"><SvgIcon name="ele-Search"/></el-button>
                          </template>
                          </el-input>
                    </el-form-item>
                  </vp-col>
                  <vp-col :span="4" >
                    <el-form-item prop="zdfkr" :rules="[validateUtils.notNull]">
                      <template #label><vp-label zh="反馈人" en="Feedback Person"/></template>
                        <el-input
                          v-model="processExtFormData.zdfkr"  readonly
                          @blur="processExtFormData.zdfkr = $event.target.value.trim()"
                        >
                        <template #append>
                          <el-button @click="handleSearchZdfkr"><SvgIcon name="ele-Search"/></el-button>
                        </template>
                        </el-input>
                  </el-form-item>
                </vp-col>
                <vp-col :span="4" >
                  <el-form-item prop="fkqx">
                    <template #label><vp-label zh="反馈期限" en="Feedback Deadline"/></template>
                    <el-date-picker
                      v-model="processExtFormData.fkqx"
                      type="date"
                      style="width: 100%"
                      value-format="YYYY-MM-DD"
                    ></el-date-picker>
                  </el-form-item>
                </vp-col>
                <vp-col :span="1" >
                  <el-form-item prop="cljg">
                    <template #label><vp-label zh="说明" en="Description"/></template>
                    <el-input
                          v-model="processExtFormData.sm"
                          maxlength="1300"
                          :autosize="{ minRows: 3}"
                          type="textarea"
                      />
                  </el-form-item>
                </vp-col>
                <vp-col :span="1" >
                  <el-form-item prop="cljg">
                    <template #label><vp-label zh="其他说明" en="Ohter Description"/></template>
                    <el-input
                          v-model="processExtFormData.cljg"
                          maxlength="1300"
                          :autosize="{ minRows: 3}"
                          type="textarea"
                      />
                  </el-form-item>
                </vp-col>
              </el-row>
              <el-row v-if="isValid && formData.jb == 10 && formData.lx == 20 && processExtFormData.cnbs == 1">
                <vp-col :span="4" >
                  <el-form-item :label="$t('voluntaryDept.item.clr')" prop="clr" :rules="[validateUtils.notNull]">
                      <el-input
                        v-model="processExtFormData.clr"  readonly
                        @blur="processExtFormData.clr = $event.target.value.trim()"
                      >
                      <template #append>
                        <el-button @click="handleSearchClr"><SvgIcon name="ele-Search"/></el-button>
                      </template>
                      </el-input>
                </el-form-item>
              </vp-col>
              <vp-col :span="4" >
                <el-form-item :label="$t('voluntaryDept.item.clrq')" prop="clrq">
                  <el-date-picker
                    v-model="processExtFormData.clrq"
                    type="date"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"
                  ></el-date-picker>
                </el-form-item>
              </vp-col>
              <vp-col :span="1" >
                <el-form-item prop="cljg" :label="$t('voluntaryDept.item.cnsm1')"  >
                  <el-input
                        v-model="processExtFormData.cljg"
                        maxlength="1300"
                        :autosize="{ minRows: 3}"
                        type="textarea"
                    />
                </el-form-item>
              </vp-col>
              </el-row>
              <el-row v-if="isValid && formData.jb == 10  && formData.lx == 20 && processExtFormData.cnbs == 1">
                <FileListCard
                  class="mt4 w100"
                  :attachmentList.sync="processExtFormData.clglfjAttachemts"
                  @attachmentListEmit="getAttachmentListEmit($event)"
                >
                </FileListCard>
              </el-row>  
              <el-row v-if="isValid && formData.jb == 20 && processExtFormData.cnbs == 1">
                <vp-col :span="1">
                  <el-form-item prop="cljg">
                    <template #label><vp-label zh="指定责任部门" en="Designated Responsible Dept."/></template>
                    <vp-table ref="tableRef" :data="processExtFormData.handles" row-key="id">
                      <el-table-column align="center" width="90" >
                          <template #header>
                            <el-button circle @click="handleAddHistory()"
                              ><SvgIcon name="ele-Plus"></SvgIcon
                            ></el-button>
                          </template>
                          <template #default="scope" >
                            <el-button circle @click="handleDeleteHistory(scope.row.$index)"
                              ><SvgIcon name="ele-Minus"></SvgIcon
                            ></el-button>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="zrbm"
                        >
                          <template #header><vp-label zh="责任部门" en="Responsible Dept."/></template>
                          <template #default="scope">
                              <el-form-item  :prop="`handles[${scope.$index}].zrbm`" :rules="[validateUtils.notNull]">
                                  <el-input
                                    v-model="scope.row.zrbm"
                                    @blur="scope.row.zrbm = $event.target.value.trim()"
                                    readonly
                                  >
                                  <template #append>
                                    <el-button @click="handleSearchDprt(scope.row)"><SvgIcon name="ele-Search"/></el-button>
                                  </template>
                                  </el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="zdfkr"
                        >
                         <template #header><vp-label zh="反馈人" en="Feedback Person"/></template>
                          <template #default="scope">
                              <el-form-item :prop="`handles[${scope.$index}].zdfkr`" :rules="[validateUtils.notNull]">
                                  <el-input
                                    v-model="scope.row.zdfkr"
                                    @blur="scope.row.zdfkr = $event.target.value.trim()"
                                    readonly
                                  >
                                  <template #append>
                                    <el-button @click="handleSearchUser(scope.row)"><SvgIcon name="ele-Search"/></el-button>
                                  </template>
                                  </el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="fkqx"
                          show-overflow-tooltip
                        >
                          <template #header><vp-label zh="反馈期限" en="Feedback Deadline"/></template>
                          <template #default="scope">
                              <el-form-item prop="fkqx" >
                                <el-date-picker
                                  v-model="scope.row.fkqx"
                                  type="date"
                                  style="width: 100%"
                                  value-format="YYYY-MM-DD"
                                ></el-date-picker>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="sm"
                          show-overflow-tooltip
                        >
                          <template #header><vp-label zh="说明" en="Description"/></template>
                          <template #default="scope">
                              <el-form-item prop="sm" >
                                  <el-input
                                    v-model="scope.row.sm"
                                    @blur="scope.row.sm = $event.target.value.trim()"
                                    maxlength="1300"
                                  >
                                  </el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                    </vp-table>
                  </el-form-item>  
                </vp-col>
              </el-row>
              <el-row  v-if="isValid && formData.jb == 20 && processExtFormData.cnbs == 1">
                <vp-col :span="1" >
                  <el-form-item prop="cnsm">
                    <template #label><vp-label zh="其他说明" en="Other Description"/></template>
                    <el-input
                          v-model="processExtFormData.cnsm"
                          maxlength="1300"
                          :autosize="{ minRows: 3}"
                          type="textarea"
                      />
                  </el-form-item>
                </vp-col>  
              </el-row>
          </el-form> 
        </vp-card>
      </el-tab-pane>
      <el-tab-pane>
        <template #label><vp-label zh="流程记录" en="Process Record"/></template>
        <ProcessHistory :processInsId="processInsId" :hiddenCreator="formData.nmbs === 1" v-if="formData.id"/>
      </el-tab-pane>
      <el-tab-pane>
        <template #label><vp-label zh="流程图" en="Process Chart"/></template>
        <ProcessView :processInsId="processInsId" />
      </el-tab-pane>
    </el-tabs>
    <StatusBar
      :id="formData.id"
      :status="formData.zt"
      :isValid="formData.yxbs"
    />
    <PageBottom>
      <VpProcessToolBar 
        :process-ins-id="processInsId" 
        :task-id="taskId" 
        :loading="submitLoading" 
        :before-show-fn="beforeShowFn"
        :after-agree-fn="afterAgreeFn"
        :set-loading-fn="(_loading: boolean) => { submitLoading = _loading }"
      />
    </PageBottom>
    <UserDialog ref="userDialogRef"></UserDialog>
    <DepartmentDialog ref="departmentRef"></DepartmentDialog>
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  toRefs,
} from "vue";
import request from "/@/utils/request";
import ProcessHistory from '/@/components/vp/workflow/ProcessHistory.vue';
import ProcessView from "/@/components/vp/workflow/ProcessView.vue";
import ProcessHandle from "/@/components/vp/workflow/VpProcessHandle.vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import VoluntaryDept from "./VoluntaryDept.vue";
import PageBottom from '/@/components/vp/PageBottom/index.vue';
import validateUtils from "/@/utils/validateUtils";
import UserDialog from '/@/components/vp/user/VpUserDialog.vue';
import DepartmentDialog from '/@/components/vp/department/VpDepartmentDialog.vue';
import FileListCard from '/@/components/vp/file/VpFileListCard.vue';
import mittBus from '/@/utils/mitt';
import StatusBar from '/@/components/vp/status/StatusBar.vue';
import VpProcessToolBar from '/@/components/vp/workflow/VpProcessToolBar.vue';

export default defineComponent({
  name: "auditVoluntaryDept",
  props: {
    businessId: String,
    taskId: String,
    processInsId: String,
  },
  components: { ProcessHistory, ProcessView, ProcessHandle, VoluntaryDept, PageBottom, validateUtils, UserDialog, DepartmentDialog, FileListCard, StatusBar, VpProcessToolBar },
  setup(props) {
    const state = reactive({
      loading: false,
      submitLoading: false,
      type: "audit",
      formData: {
        id: "",
        zt: 10,
        yxbs: 1,
        jb: null,
        processHandle: {},
      },
      processExtFormData: {
        cnbs: null,
        cnsm: "",
        clrid: "",
        clrq: "",
        cljg: "",
        clr: "",
        clglfjAttachemts: [],
        handles: [],
        zrbm: "",
        zrbmid: "",
        zdfkr: "",
        zdfkrid: "",
        fkqx: "",
        sm: "",
      }
    });

    const loadWorkflow = () => {};
    onMounted(() => {
      loadWorkflow();
    });
    const route = useRoute();
    const processHandleRef = ref();
    const taskRef = ref();

    const processExtFormRef = ref();
    const userDialogRef = ref();
    const isValid = ref(true);
    const departmentRef = ref();
    /**
     * 流程操作变动事件
     */
    const handleOperateChanged = (operate: boolean)=>{
        isValid.value = operate;
    }

    const getData = (data: any) => {
      state.formData = data;
    };

    const handleSearchClr = () =>{
      userDialogRef.value.handleOpen({
        type: 1,
        multi: false,
        selected: state.processExtFormData.clrid,
        callback: (data: any) => {
          state.processExtFormData.clrid = data.yhid;
          state.processExtFormData.clr = data.xm;
        }
      });
    }
    const handleSearchZdfkr = () =>{
      userDialogRef.value.handleOpen({
        type: 1,
        multi: false,
        selected: state.processExtFormData.zdfkrid,
        callback: (data: any) => {
          state.processExtFormData.zdfkrid = data.yhid;
          state.processExtFormData.zdfkr = data.xm;
        }
      });
    }

    const handleAddHistory = () => {
      state.processExtFormData.handles.push({});
    };

    const handleDeleteHistory = (index: number) => {
        state.processExtFormData.handles.splice(index, 1);
      };

      const handleSearchUser = (row: any) =>{
      userDialogRef.value.handleOpen({
        type: 1,
        multi: false,
        selected: row.zdfkrid,
        callback: (data: any) => {
          row.zdfkrid = data.yhid;
          row.zdfkr = data.xm;
        }
      });
    }

      const handleSearchDprt =(row: any) =>{
        departmentRef.value.handleOpen({
          selectedId: row.zrbmid,
          callback: (data: any) => {
            row.zrbmid = data.id;
            row.zrbm = data.dprtname;
          }
        });
      }

    const getAttachmentListEmit = (list: any, lx: number) => {
          state.processExtFormData.clglfjAttachemts = list;
    };

    //同意前操作
    const beforeShowFn = () => {
      state.submitLoading = true;
      const promise1 = processExtFormRef.value.validate();
      const promise2 = new Promise((resolve, reject) => { 
          if(state.formData.jb == 20 && state.processExtFormData.cnbs == 1 && (state.processExtFormData.handles.length == 0 || !state.processExtFormData.handles)){
            ElMessage.error("请指定责任部门");
            reject();
          }
          resolve(true);
      })
      return Promise.all([promise1, promise2]).finally(()=>{state.submitLoading = false;});
    }
    
    //同意后操作
    const afterAgreeFn = (processHandle: any) => { 
      state.submitLoading = true;
      request.post("/voluntary/dept/audit", {
          ...state.formData,
          processHandle: {
              processInsId: props.processInsId,
              taskId: props.taskId,
              ...processHandle,
          },
          cnbs: isValid.value ? state.processExtFormData.cnbs : null,
          cnsm: isValid.value && state.processExtFormData.cnbs == 0 && state.formData.jb == 10 ? state.processExtFormData.cnsm : isValid.value && state.processExtFormData.cnbs == 1 && state.formData.jb  == 20 ? state.processExtFormData.cnsm : '',
          clrid: isValid.value && state.processExtFormData.cnbs == 1 && state.formData.jb == 10? state.processExtFormData.clrid : '',
          clrq: isValid.value && state.processExtFormData.cnbs == 1 && state.formData.jb == 10? state.processExtFormData.clrq : '',
          cljg: isValid.value && state.processExtFormData.cnbs == 1 && state.formData.jb == 10? state.processExtFormData.cljg : '',
          clr: isValid.value && state.processExtFormData.cnbs == 1 && state.formData.jb == 10? state.processExtFormData.clr : '',
          clglfjAttachemts: isValid.value && state.processExtFormData.cnbs == 1 && state.formData.jb == 10 ? state.processExtFormData.clglfjAttachemts : null,
          handles: isValid.value && state.processExtFormData.cnbs == 1 && state.formData.jb == 20 ? state.processExtFormData.handles : null,
          deptHandle: {
            zrbmid: isValid.value && state.processExtFormData.cnbs == 1 && state.formData.jb == 10 && state.formData.lx == 10 ? state.processExtFormData.zrbmid : '',
            zrbm: isValid.value && state.processExtFormData.cnbs == 1 && state.formData.jb == 10 && state.formData.lx == 10 ? state.processExtFormData.zrbm : '',
            fkqx: isValid.value && state.processExtFormData.cnbs == 1 && state.formData.jb == 10 && state.formData.lx == 10 ? state.processExtFormData.fkqx : '',
            zdfkrid : isValid.value && state.processExtFormData.cnbs == 1 && state.formData.jb == 10 && state.formData.lx == 10 ? state.processExtFormData.zdfkrid : '',
            sm: isValid.value && state.processExtFormData.cnbs == 1 && state.formData.jb == 10 && state.formData.lx == 10 ? state.processExtFormData.sm : '',
          }
      }).then(()=>{
          mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
          ElMessage.success("办理完毕/Completed Processing");
      }).catch(()=>{
      }).finally(()=>{
          state.submitLoading = false;
      })
    }

    return {
      ...toRefs(state),
      ...toRefs(props),
      processHandleRef,
      taskRef,
      validateUtils,
      isValid,
      handleOperateChanged,
      getData,
      processExtFormRef,
      handleSearchClr,
      userDialogRef,
      handleAddHistory,
      handleDeleteHistory,
      handleSearchDprt,
      departmentRef,
      handleSearchUser,
      getAttachmentListEmit,
      handleSearchZdfkr,
      beforeShowFn,
      afterAgreeFn,
    };
  },
});
</script>